package db

import (
	"database/sql"
	"errors"
	"go-fast/pkg/config"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

const (
	MysqlDriver   = "mysql"
	PostgreDriver = "postgre"
	SqliteDiver   = "sqlite"
)

type SqlDB struct {
	GormDB *gorm.DB
	SqlDB  *sql.DB
}

func NewDB(config *config.DBConfig) (*SqlDB, error) {
	if config == nil {
		panic("not init db config")
	}
	var (
		gormDB *gorm.DB
		sqlDB  *sql.DB
		err    error
	)
	switch config.Driver {
	case MysqlDriver:
		gormDB, err = gorm.Open(mysql.Open(config.Dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.LogLevel(config.LogLever))})

	case PostgreDriver:
		gormDB, err = gorm.Open(postgres.Open(config.Dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.LogLevel(config.LogLever))})
	case SqliteDiver:
		gormDB, err = gorm.Open(sqlite.Open(config.Dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.LogLevel(config.LogLever))})
	default:
		return nil, errors.New("db: unsupported db driver: " + config.Driver)
	}

	sqlDB, err = gormDB.DB()
	if err != nil {
		return nil, err
	}
	// 设置连接池参数
	sqlDB.SetMaxIdleConns(config.MaxIdleConn)
	sqlDB.SetMaxOpenConns(config.MaxOpenConn)
	sqlDB.SetConnMaxIdleTime(time.Second * time.Duration(config.ConnMaxLifetime))

	return &SqlDB{GormDB: gormDB, SqlDB: sqlDB}, nil
}

func (d *SqlDB) Close() {
	d.SqlDB.Close()
}
